package netty.code;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

public class NettyServerHandler extends SimpleChannelInboundHandler<Long> {
    /**
     * 读取数据
     * @param ctx: 上下文对象，其中包含 pipeline、channel...
     * @param msg: 客户端发送数据
     * @throws Exception
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Long msg) throws Exception {
        Channel channel = ctx.channel();
        System.out.println("接收到客户端: " + channel.remoteAddress() + " 发送消息: " + msg);
    }

    /**
     * 读取数据完毕
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        Long msg = 111111L;
        System.out.println("服务器回复消息: " + msg);
        ctx.writeAndFlush(msg);
    }

    /**
     * 处理异常, 并关闭通道
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println(cause.getMessage());
        ctx.close();
    }
}
